<template>
  <div class="cooper-members">
    <div class="cooper-members-left">
      <el-tree
        empty-text="暂无数据"
        style="max-width: 400px"
        ref="teachertreeRef"
        :props="personprops"
        :data="teacherdata"
        node-key="id"
        show-checkbox
        default-expand-all
        filterable
        @check-change="handleCheckTeacher"
      />
    </div>
    <div class="cooper-members-right">
      <div class="wrapper">
        <el-select-v2
          v-model="value"
          filterable
          remote
          :remote-method="remoteMethod"
          clearable
          :options="selectOptions"
          :loading="loading"
          placeholder="请输入账号名搜索"
          @change="handleSelect"
        />
        <MemberList
          :members="members"
          :options="options"
          @change="handleMemberChange"
          :multiple="multiple"
        >
        </MemberList>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { useStore } from 'vuex'
import MemberList from './MemberList.vue'
import auth from '@/management/api/eco/auth'

// import { searchUserByName as getUserList } from '@/management/api/eco/auth'
import {
  type IMember,
  type ListItem,
  type UserRole,
  roleLabels
} from '@/management/utils/types/formsTypes'
import { CODE_MAP } from '@/management/api/eco/base'

import { queryTeacherList } from '@/management/api/basedata'
import { arrayToTree } from '@/management/utils/index'
import { ElTree } from 'element-plus'

const store = useStore()
const props = withDefaults(
  defineProps<{
    members?: IMember[]
    options?: ListItem[]
    multiple?: boolean
  }>(),
  {
    members: () => [],
    options: () => {
      return Object.keys(roleLabels).map((key) => ({
        label: roleLabels[key as UserRole],
        value: key
      }))
    },
    multiple: false
  }
)
const emit = defineEmits(['select', 'change'])

const value = ref('')
const selectOptions = ref<ListItem[]>([])
const loading = ref(false)

const remoteMethod = async (query: string) => {
  if (query !== '') {
    loading.value = true
    const res: any = await auth.searchUserByName({realName: query, roleId: "1000000002"})
    if (res?.serverResult?.resultCode === CODE_MAP.SUCCESS) {
      selectOptions.value = res?.pageInfo?.list.map((item: any) => {
        // 不可以选中自己
        const currentUser = item.userId === (window as any).$app.user.userId
        return {
          ...item,
          value: item.userId,
          label: item.realName,
          disabled: props.members.map((item) => item.userId).includes(item.userId) || currentUser
        }
      })
      loading.value = false
    }
  } else {
    selectOptions.value = []
  }
}
const handleSelect = (val: string) => {
  value.value = ''
  emit('select', val, selectOptions.value?.find((item) => item.value === val)?.label)
}
const handleMemberChange = (val: any) => {
  emit('change', val)
}

const personprops = {
  label: 'name',
  value: 'id',
  children: 'children',
}
interface PersonTree {
  id: string
  name: string
  children?: PersonTree[]
}
const teacherdata = ref<any>([])
const modelValue = ref<any[]>([])
  const teachertreeRef = ref<InstanceType<typeof ElTree>>()
const handleCheckTeacher = (
  data: PersonTree,
  checked: boolean,
  indeterminate: boolean
) => {
  let selected: any[] = (modelValue.value as Array<any>)?.map((v: any) => v.id) || [];
  (teachertreeRef.value!.getCheckedNodes(false, false) || []).forEach((titm: any) => {
    if (selected.indexOf(titm.id) === -1) {
      modelValue.value.push({
        id: titm.id,
        name: titm.name,
        parentId: titm.parentId,
        nodeType: titm.nodeType,
      })
      emit('select', titm.id, titm.name)
    }
  })
}
const getTeacherList = async () => {
  const resp: any = await queryTeacherList({orgId: (window as any).$app.user.orgId})
  const listp = (resp?.result || []).filter((item: any) => item.nodeType === '2').map((titm: any) => {
    return {
      id: titm.nodeId,
      name: titm.nodeName,
      value: titm.nodeId,
      label: titm.nodeName,
      ...titm
    }
  })
  let treelistp = arrayToTree(listp, 'nodeId', 'parentId', 'children')
  teacherdata.value = treelistp
}
onMounted(() => {
  getTeacherList()
})
</script>
<style lang="scss" scoped>
.wrapper {
  width: 100%;
}

.cooper-members {
    display: flex;
    width: 100%;

    .cooper-members-left {
      width: 300px;
      border: 1px solid #e4e4e4;
    }
    .cooper-members-right {
      width: calc(100% - 310px);
      margin-left: 10px;
    }
    :deep(.el-tree) {
      height: 390px;
      overflow-y: auto;
    }
  }
</style>
